package com.tajiang.business.businesscount.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tajiang.business.R;
import com.tajiang.business.common.activity.BaseActivity;
import com.tajiang.business.common.utils.PostDataTools;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.common.widget.WheelView;
import com.tajiang.business.mess.data_base_op.DBHelperGetProvinces;
import com.tajiang.business.model.City;
import com.tajiang.business.model.Province;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 添加银行卡
 */
public class AddBankCardActivityActivity extends BaseActivity {

    @BindView(R.id.add_bank_card_name)
    EditText edtName;

    @BindView(R.id.add_bank_card_id)
    EditText edtId;

    @BindView(R.id.add_bank_card_bank)
    TextView tvBank;

    @BindView(R.id.add_bank_card_city)
    TextView tvCity;

    @BindView(R.id.add_bank_card_commit)
    Button btnCommit;

    @BindView(R.id.wv_choose_shen_fen)
    WheelView wvChooseShenFen;

    @BindView(R.id.wv_choose_city)
    WheelView wvChooseCity;

    @BindView(R.id.tv_cancel)
    TextView tvCancel;

    @BindView(R.id.tv_finish)
    TextView tvFinish;

    @BindView(R.id.add_bank_card_bottom_city)
    LinearLayout layoutCity;

    private static final int MSG_GET_ASSETS = 1; //消息类型：获取资源
    private DBHelperGetProvinces dbHelperGetProvinces;
    private List<Province> provinceList;

    private HandlerThread mGetAssetsThread;
    private MyHandler mGetAssetsHandler;

    private String province;
    private String city;
    private int bankId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initTopBar() {
        setTitle("账户信息");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_add_bank_card_activity);
    }

    @Override
    protected void initData() {

        Intent intent = getIntent();
        if(intent != null){

            edtName.setText(intent.getStringExtra("owner"));
            edtId.setText(intent.getStringExtra("no"));
            tvBank.setText(intent.getStringExtra("bankName"));

            bankId = intent.getIntExtra("bankId", 0);
            province = intent.getStringExtra("prov");
            city = intent.getStringExtra("city");

            tvCity.setText(city);
        }

        dbHelperGetProvinces = new DBHelperGetProvinces(this);
        mGetAssetsHandler = new MyHandler();

        layoutCity.setVisibility(View.GONE);
        wvChooseShenFen.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                List<City> cities = dbHelperGetProvinces.getCity(provinceList.get(selectedIndex - 1).getAreaId());
                List<String> cityNames = new ArrayList<String>();
                for (City city : cities) {
                    cityNames.add(city.getAreaName());
                }
                wvChooseCity.setOffset(1);
                wvChooseCity.setItems(cityNames);
                wvChooseCity.setSeletion(0);
            }
        });

        wvChooseCity.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {

            }
        });

        new Thread(new GetCityAssetsRunnable()).start();
    }

    private void updateWheelView() {

        if (provinceList != null) {
            List<String> provinces = new ArrayList<String>();

            for (Province province : provinceList) {
                provinces.add(province.getAreaName());
            }
            wvChooseShenFen.setOffset(1);
            wvChooseShenFen.setItems(provinces);

            List<City> cities = dbHelperGetProvinces.getCity(provinceList.get(0).getAreaId());
            List<String> cityNames = new ArrayList<String>();
            for (City city : cities) {
                cityNames.add(city.getAreaName());
            }
            wvChooseCity.setOffset(1);
            wvChooseCity.setItems(cityNames);
            wvChooseCity.setSeletion(0);
        }
    }

    class GetCityAssetsRunnable implements Runnable {
        public void run() {
            Message msg = new Message();
            msg.what = MSG_GET_ASSETS;
            //读取资源文件，初始化省份和城市选择器
            provinceList = dbHelperGetProvinces.getProvince();
            mGetAssetsHandler.sendMessage(msg);
        }
    }

    //读取资源文件，初始化省份和城市选择器
    public void getFromAssets() {

        String fileName = "province_city.txt";
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName), "UTF-8");
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String jsonData = "";
            while ((line = bufReader.readLine()) != null)
                jsonData += line;
            Gson gson = new Gson();
            Type type = new TypeToken<List<Province>>() {
            }.getType();

            provinceList = gson.fromJson(jsonData, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyHandler extends Handler {
        public MyHandler() {

        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_GET_ASSETS:

                    updateWheelView();
                    break;
            }
        }
    }

    @OnClick(R.id.tv_cancel)
    public void onCancelClick() {

        layoutCity.setVisibility(View.GONE);
    }

    @OnClick(R.id.tv_finish)
    public void onFinishClick() {

        layoutCity.setVisibility(View.GONE);

        province = wvChooseShenFen.getSeletedItem();
        city = wvChooseCity.getSeletedItem();

        tvCity.setText(city);
    }

    @OnClick(R.id.add_bank_card_layout_city)
    public void onAddressClick() {

        layoutCity.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.add_bank_card_bank)
    public void bank(){

        Intent intent = new Intent(this, SelectBankActivity.class);
        startActivityForResult(intent, 0x0011);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 0x0011 && resultCode == RESULT_OK){

            bankId = data.getIntExtra("bankId", 0);
            tvBank.setText(data.getStringExtra("bankName"));
        }
    }

    @OnClick(R.id.add_bank_card_commit)
    public void commit(){

        String name = edtName.getText().toString();
        String id = edtId.getText().toString();
        String bank = tvBank.getText().toString();

        if(TextUtils.isEmpty(name)){
            ToastUtils.showShort("持卡人不能为空");
            return;
        }

        if(TextUtils.isEmpty(id)){
            ToastUtils.showShort("卡号不能为空");
            return;
        }

        if(TextUtils.isEmpty(bank)){
            ToastUtils.showShort("银行不能为空");
            return;
        }

        if(TextUtils.isEmpty(city)){
            ToastUtils.showShort("开户行所在地不能为空");
            return;
        }

        PostDataTools.acct_setwithdraw(this, name, id, bankId, province, city, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                if(flag){
                    finish();
                }
            }
        });
    }

}
